package com.wdb.common.configurer.subject;

import feign.Feign;
import feign.RequestInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.Resource;

@Configuration
@ConditionalOnClass({Feign.class, FeignClient.class})
public class SubjectContextConfigurer extends WebMvcConfigurerAdapter {
    @Value("${proxy.target}")
    private String proxy_target;

    @Value("${proxy.subject}")
    private String proxy_subject;

    @Resource
    private Environment env;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Bean
    public RequestInterceptor proxyInterceptor() {
        SubjectProxyInterceptor interceptor = new SubjectProxyInterceptor();

        interceptor.setProxy_target(proxy_target);

        interceptor.setProxy_subject(proxy_subject);

        if (logger.isDebugEnabled()) {
            logger.info("[{}]", "added subject proxy interceptor");
        }
        return interceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (!env.getProperty("component.gateway", boolean.class, false)) {
            SubjectContextInterceptor interceptor = new SubjectContextInterceptor();

            interceptor.setProxy_target(proxy_target);

            interceptor.setProxy_subject(proxy_subject);

            registry.addInterceptor(interceptor);

            if (logger.isDebugEnabled()) {
                logger.info("[{}]", "added subject interceptor");
            }
        }
    }
}
